import axios from 'axios'
import {Message} from 'element-ui'
import router from "../router/router"
import storage from '../storage/index'

axios.defaults.baseURL = '/api'
axios.defaults.timeout = 8000

/*************** 拦截器***********************/

// http request 请求拦截器，有token值则配置上token值
axios.interceptors.request.use((config) => {
    let token = storage.getItem("token");
    // 每次发送请求之前判断是否存在token，如果存在，则统一在http请求的header都加上token，不用每次请求都手动添加了
    if (token) {
        config.headers['Access-Token'] = token;
    }
    return config;
}, (err) => {
    Message.error(err)
    return Promise.reject(err);
});

// http response 服务器响应拦截器
axios.interceptors.response.use((response) => {
        switch (response.data.status) {
            case 0:
                return response;
            case 10002: //未登录
                //localStorage.removeItem("token");
                //localStorage.removeItem("username");
                router.replace({
                    path: '/login',
                });
                break
            case 10009:
                Message.error(response.data.message)
                break
            default:
                return response;
            }
    }, (error) => {
        //Message.error(error)
        return Promise.reject(error)
})
/*************** END 拦截器***********************/

/****************发送请求**************************/

export default {
    get(url, data = {}) {
        return ajax(url, data, 'GET')
    },

    post(url, data = {}) {
        return ajax(url, data, 'POST');
    }
}
function ajax(url, data = {}, type = 'GET') {
    return new Promise((resolve, reject) => {
        // 执行异步ajax请求
        let promise;
        if (type === 'GET') {
            // 准备url query参数数据
            let dataStr = ''; //数据拼接字符串
            Object.keys(data).forEach(key => {
                dataStr += key + '=' + data[key] + '&'
            });
            if (dataStr !== '') {
                dataStr = dataStr.substring(0, dataStr.lastIndexOf('&'));
                url = url + '?' + dataStr
            }
            // 发送get请求
            promise = axios.get(url)
        } else if (type === 'POST') {
            // 发送post请求
            promise = axios.post(url, data)
        }
        promise.then(function (response) {
            // 成功了调用resolve()
            if (response) {
                resolve(response.data)
            } else {
                // alert("当前请求的返回值出现错误,请检查！", "error")
            }
        }).catch(function (error) {
            //失败了调用reject()
            reject(error)
        })
    })
}


